import Taro from '@tarojs/taro'
import api from '@API'
import { ACQUIRE_CHANNEL, ROUTER_ID_MAP } from '@CONSTANTS/app'
import { Analytic_Type } from '@CONSTANTS/analytic'
import Scenes from '@NAVIGATION/scenes'
import { getClientType, getPlatform, getPathname, searchRouterKey } from '@UTILS/common'
import { dataFetch } from '@pier88health/p8h-common'
import { getStorageSync } from '@UTILS/localStorage'
import { USER_STATUS } from '@CONSTANTS/profile'

export function getUserDepartmentAndInstitution(data, language, placeholder) {
  if (!data || !language) {
    return ''
  }
  const { Department, SubDepartment, Affiliation } = data
  const departmentName = Department ? Department.Name : {}
  const subDepartmentName = SubDepartment ? SubDepartment.Name : {}
  const affiliationName = Affiliation ? Affiliation.Name : {}
  const departmentText = departmentName && departmentName[language] || ''
  const subDepartmentText = subDepartmentName && subDepartmentName[language] || ''
  const institutionText = affiliationName ? affiliationName[language] : ''
  const departmentDisplayText = subDepartmentText || departmentText
  if (!departmentDisplayText || !institutionText) return departmentDisplayText || institutionText
  return `${departmentDisplayText}${placeholder || ' | '}${institutionText}`
}

export async function commonInitUser(dispatchInitUser, dispatchVisitorLogin) {
  try {
    const user = await Taro.getStorageSync('user')
    if (user) {
      dispatchInitUser(user)
    } else {
      dispatchVisitorLogin()
    }
  } catch (e) {
    console.log('error,', e)
  }
}
const AcquireChannelInfo = {
  AcquireChannel: ACQUIRE_CHANNEL[Taro.getEnv()]
}

const qrCodeScan = (query, path) => {
  const url = decodeURIComponent(query.q)
  const params = dataFetch.getQueryParams(url)
  const subChannel = params?.subChannel || params?.sC
  const channel = params?.AcquireChannel || params?.aC
  subChannel && (AcquireChannelInfo.SubChannel = subChannel)
  channel && (AcquireChannelInfo.AcquireChannel = channel)
  if (path.indexOf('PatientRegistration') > -1 || path.indexOf('doctorDetail') > -1) {
    AcquireChannelInfo.AcquireChannel = channel || ACQUIRE_CHANNEL.DoctorQRCode
    AcquireChannelInfo.Invitor = { InvitorUserType: 'Doctor', UserId: params?.p8Id }
    return
  }
  if (path.indexOf('DecisionFlowIndex') > -1) {
    AcquireChannelInfo.AcquireChannel = channel || ACQUIRE_CHANNEL.DIAGNOSIS
    AcquireChannelInfo.Invitor = { InvitorUserType: 'Doctor', UserId: params?.doctorId }
  }
}

const MINIPROGRAM_CODE_SCAN = ['1047', '1048', '1049']
const PUBLIC_NUMBER_MSG = ['1074', '1082']
const PUBLIC_NUMBER = ['1035', '1102']

const handleWebAcquireChannel = () => {
  const url = window.location.href
  const pathname = getPathname()
  const comparePathname = pathname === '/' ? Scenes.homePage : pathname
  AcquireChannelInfo.LandingSource = searchRouterKey(comparePathname)
  const params = dataFetch.getQueryParams(url)
  const id = ROUTER_ID_MAP[comparePathname]
  id && params[id] && (AcquireChannelInfo.LandingId = params[id])
}
// 小程序场景值文档 https://developers.weixin.qq.com/miniprogram/dev/reference/scene-list.html
const handleWxAcquireChannel = options => {
  const {
    path, scene, query, referrerInfo
  } = options
  const sceneStr = `${scene}`
  const appId = referrerInfo?.appId || query.appid
  Taro.tracker.trackEvent(Analytic_Type.tap_wmp_onLaunch.eventId, { scene: sceneStr })
  const isScanQrCode = sceneStr === '1011' || sceneStr === '1012' || sceneStr === '1013'
  console.log('scanStr', options, sceneStr, path, scene, query, isScanQrCode, appId)
  const pathStr = `/${path}`
  AcquireChannelInfo.LandingSource = searchRouterKey(pathStr)
  AcquireChannelInfo.SceneId = scene
  appId && (AcquireChannelInfo.AppId = appId)
  const id = ROUTER_ID_MAP[pathStr]
  if (query?.invitorUserId) {
    const userInvitor = { InvitorUserType: 'WMP', UserId: query?.invitorUserId }
    AcquireChannelInfo.UserInvitor = userInvitor
    updateUserInvitor(userInvitor)
  }
  id && query[id] && (AcquireChannelInfo.LandingId = query[id])
  if (isScanQrCode) {
    qrCodeScan(query, path)
    return
  }
  const subChannel = query?.subChannel || query?.sC
  const channel = query?.AcquireChannel || query?.aC || ACQUIRE_CHANNEL[sceneStr]
  subChannel && (AcquireChannelInfo.SubChannel = subChannel)
  channel && (AcquireChannelInfo.AcquireChannel = channel)
  if (MINIPROGRAM_CODE_SCAN.includes(sceneStr) && query) {
    const queryObj = dataFetch.getQueryParams(`?${decodeURIComponent(query.scene)}`)
    AcquireChannelInfo.AcquireChannel = queryObj.Channel || queryObj.aC
    AcquireChannelInfo.SubChannel = queryObj.subChannel || queryObj.sC
    return
  }
  if (PUBLIC_NUMBER.includes(sceneStr)) {
    AcquireChannelInfo.AcquireChannel = channel || ACQUIRE_CHANNEL.PublicNumber
    return
  }
  if (PUBLIC_NUMBER_MSG.includes(sceneStr)) {
    switch (pathStr) {
      case Scenes.decisionFlowIndex:
        AcquireChannelInfo.Invitor = { InvitorUserType: 'Doctor', UserId: query?.doctorId }
        break
      case Scenes.patientRegistration:
        AcquireChannelInfo.Invitor = { InvitorUserType: 'Doctor', UserId: query?.p8Id }
        break
      case Scenes.surveyPatientRegister:
        AcquireChannelInfo.Invitor = { InvitorUserType: 'Doctor', UserId: query?.doctorId }
        AcquireChannelInfo.AcquireChannel = channel || ACQUIRE_CHANNEL.SurveyPatientRegister
        break
      default:
        break
    }
  }
}
export const setAcquireChannelInfo = options => {
  const { isWeb, isWX } = getPlatform()
  console.log('onLaunch', options)
  isWeb && handleWebAcquireChannel(options)
  isWX && handleWxAcquireChannel(options)
}
export const setAcquireChannel = channel => {
  if (!channel) return
  AcquireChannelInfo.AcquireChannel = channel
}
export const getAcquireChannelInfo = () => AcquireChannelInfo
export const setInvitorInfo = scanInvitorInfo => {
  AcquireChannelInfo.Invitor = scanInvitorInfo
}

export const scanQrCodeLog = async params => {
  if (!params) return
  try {
    const reqParams = { ...params, Source: getClientType() }
    await api.scanCodeLog(reqParams)
  } catch (err) {
    Taro.showToast({ icon: 'none', title: err.message || err })
  }
}

export const updateUserInvitor = async userInvitor => {
  const user = await getStorageSync('user')
  if (!user || !user?.Status) return
  if (user.Status === USER_STATUS.Registered) return
  try {
    await api.updateUserInvitor({ UserInvitor: userInvitor })
  } catch (err) {
    Taro.showToast({ icon: 'none', title: err.message || err })
  }
}
